﻿// <copyright file="BooleanFormatProvider.cs" company="DotNetLib">
//
// .netlib: http://www.codeplex.com/DotNetLib
//
// This code is released under the New BSD License.
// A copy of this license is available at:
// http://www.codeplex.com/DotNetLib/license
//
// </copyright>

namespace DotNetLib
{
  using System;

  /// <summary>
  /// Provides formatting for <see cref="Boolean"/> types.
  /// </summary>
  public class BooleanFormatProvider : IFormatProvider, ICustomFormatter
  {
    /// <summary>
    /// Gets a formatter based on the requested type.
    /// </summary>
    /// <param name="formatType">The requested type.</param>
    /// <returns>The formatter if one is found.</returns>
    public object GetFormat(Type formatType)
    {
      if (formatType == typeof(ICustomFormatter))
      {
        return this;
      }
      else
      {
        return null;
      }
    }

    /// <summary>
    /// Formats a <see cref="Boolean"/> based on the supplied format strings.
    /// </summary>
    /// <param name="format">The format in which to format.</param>
    /// <param name="arg">The value to format.</param>
    /// <param name="formatProvider">The formatter to use.</param>
    /// <returns>A formatted string.</returns>
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
      if (!(arg is bool))
      {
        throw new ArgumentException("Must be a boolean type", "arg");
      }

      var value = (bool)arg;
      format = format == null ? string.Empty : format.Trim();

      if (string.Equals(format, "yn", StringComparison.OrdinalIgnoreCase))
      {
        return value ? "Yes" : "No";
      }

      var parts = format.Split('|');
      if ((parts.Length == 1 && !string.IsNullOrEmpty(format)) || parts.Length > 2)
      {
        throw new FormatException("Format string is invalid>");
      }

      if (parts.Length == 2)
      {
        return value ? parts[0] : parts[1];
      }
      else
      {
        return arg.ToString();
      }
    }
  }
}
